#include <rtthread.h>
#include <drv_gpio.h>
#include "rtdbg.h"
#include <rtdevice.h>

#define FAN_PWM     "pwm5"
#define FAN_PWM_CHN     1

#define FAN_SENSING_PIN     GET_PIN(A, 1)

struct rt_device_pwm *fan_dev;
static rt_uint32_t period = 1000000;  // 1M = 1,000,000 ns → 1kHz
static rt_uint32_t pulse = 0;    // 50% 占空比

static int fan_init(void)
{
    fan_dev = (struct rt_device_pwm*)rt_device_find(FAN_PWM);
    if(fan_dev == RT_NULL)
    {
        LOG_E("fan device find errro");
        return RT_ERROR;
    }

    if(rt_pwm_set(fan_dev, FAN_PWM_CHN, period, pulse) != RT_EOK)
    {
        LOG_E("fan device set message error");
        return RT_ERROR;
    }
    rt_pwm_enable(fan_dev, FAN_PWM_CHN);

    // rt_pin_mode(FAN_SENSING_PIN, PIN_MODE_INPUT);

    return RT_EOK;
}
INIT_COMPONENT_EXPORT(fan_init);

/**
 * 设置风枪风速, 根据挡位0-5
 * pulse_temp : 0-5
 */
void fan_set_period(rt_int8_t pulse_temp)
{
    rt_uint32_t pulse_set = 0;
    if(pulse_temp <= 0) pulse_temp = 0;
    if(pulse_temp > 5) pulse_temp = 5;
    
    if(pulse_temp == 0) pulse_set = 0;
    else if(pulse_temp > 0) pulse_set = (period/10) * pulse_temp + (period/2);
    rt_pwm_set(fan_dev, FAN_PWM_CHN, period, pulse_set);
}

rt_uint8_t fan_switch_get_pin(void)
{
    rt_ssize_t temp = rt_pin_read(FAN_SENSING_PIN);
    return temp;
}
